// pages/tabBar/car/car.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address: [],
    cartList: [],
    combinedPrice: 0,
    combinedNum: 0,
    active: false
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取缓存中的地址信息
    const address = wx.getStorageSync("address") || [];
    // 判断从哪个页面进入订单支付页
    const goodsData = wx.getStorageSync("goodsData") || {};
    // 获取缓存中的购物车商品信息
    let cartList = wx.getStorageSync("cart") || [];
    if (!goodsData.goods_name) {
      // 筛选数据
      cartList = cartList.filter(v => v.check)
      let combinedPrice = 0;
      let combinedNum = 0;
      cartList.forEach((v) => {
        combinedPrice += v.num * v.goods_price;
        combinedNum += v.num;
      });
      this.setData({
        cartList,
        combinedPrice,
        combinedNum,
        address,
        active: false
      });
    } else {
      let combinedPrice = goodsData.goods_price;
      let combinedNum = 1;
      this.setData({
        cartList: [goodsData],
        combinedPrice,
        combinedNum,
        address,
        active: true
      });
    }
    //
  },
  /**
   * 生命周期--监听页面销毁
   */
  onUnload: function () {
    if (this.data.active) {
      wx.setStorageSync('goodsData', {})
    }
  },
  // 获取位置授权
  handleAdress(e) {
    // console.log (e)
    /**
     * 1.判断用户是否已确认授权
     * （3种状态：1.以授权 scop ：true 2.取消授权 scop : false 3.初始状态 undefined）
     * 2.如果为已授权或者初始状态 ，则调用授权api
     * 3.如果为取消授权 scop：false ,则引导用户开启授
     * (api 更改，调用api无需用户授权)
     */
    wx.getSetting({
      success: (result) => {
        console.log(result);
        if (result.authSetting["scope.userInfo"] === true) {
          // 已登录
          wx.chooseAddress({
            success: (result) => {
              console.log(result);
              wx.setStorageSync("address", result);
              this.setData({
                address: result,
              });
            },
          });
        } else {
          // 未登录
          // wx.login({
          //   timeout:10000,
          //   success: (result) => {

          //   }
          // });
          console.log("未登录");
        }
      },
    });
  },
  /**
   * 读取添加购物车的缓存数据
   */
  getcartList() {
    const cartList = wx.getStorageSync("cart") || [];
    // console.log(cartList);
    this.setData({
      cartList,
    });
  },

  // 时间格式化
  formatDate() {
    let date = new Date();
    let year = date.getUTCFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let houres = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    return (
      year +
      "/" +
      month +
      "/" +
      day +
      " " +
      houres +
      ":" +
      minutes +
      ":" +
      seconds
    );
  },
  /**
   * 普通级的支付功能
   */
  // 支付功能
  handelPay() {
    wx.showModal({
      content: "确定购买商品吗?",
      success: (result) => {
        console.log(result);
        //如果点击确定
        if (!result.cancel) {
          wx.showToast({
            title: "支付成功",
            success: (result) => {
              this.orderPayAndNopay(2)
              wx.navigateTo({
                url: '../../pages/orders/index',
              });
            },
          });
        } else {
          wx.showToast({
            title: "支付失败",
            icon:'none',
            success:(res)=>{
                // console.log(res)
                this.orderPayAndNopay(1)
                wx.navigateTo({
                  url: '../../pages/orders/index',
                });
            }
          });
        }
      },
    });
  },
  /**订单支付与未支付操作 */
  orderPayAndNopay(num) {
    // 订单号
    let order_number = new Date().getTime();
    // 订单总价格
    let order_price = this.data.combinedPrice
    // 创建订单的时间
    let order_time = this.formatDate()
    // 控制订单状态
    let type = num
    if (this.data.active) {
      // 商品页面立即购买
      let goodsData = {}
      wx.setStorageSync('goodsData', goodsData)
      this.setData({
        active:false
      })
    } else {
      //购物车页面

      /**
       * 移除以支付或待支付订单,
       * 保存未被选中商品
       */
      let newCartList = wx.getStorageSync('cart')||[]
      // 获取购车未被选中的商品
      console.log(newCartList)
      newCartList = newCartList.filter(v=>!v.check)
      wx.setStorageSync('cart', newCartList)
    }
    // 获取订单
    let orders = wx.getStorageSync('orders')||[]
    
    // 添加新的订单
    orders.push({
      order_number,
      order_price,
      order_time,
      type,
      all_order:this.data.cartList,
      address:this.data.address
    })
    wx.setStorageSync('orders', orders);
  },
});